package com.ceadeal.admin.group.wechat.web;

import com.ceadeal.admin.group.wechat.service.WxCoreService;
import com.ceadeal.admin.group.wechat.util.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信公众号入口
 *
 * @author Westin Yang
 * @date 2017-03-31 19:28:33
 */
@RestController
@RequestMapping("/open/wx/entry")
public class WxEntryController {
    private static Logger log = LoggerFactory.getLogger(WxEntryController.class);

    @Autowired
    private WxCoreService wxCoreService;

    /**
     * 描述：验证url和token
     *
     * @param
     * @return
     * @throws
     *
     * @author Westin Yang
     * @date 2017-03-31 19:36:25
     */
    @GetMapping
    public String get(HttpServletRequest request) {
        log.info("验证微信公众号 => 开始");

        String signature = request.getParameter("signature");   // 微信加密签名
        String timestamp = request.getParameter("timestamp");   // 时间戮
        String nonce = request.getParameter("nonce");           // 随机数
        String echostr = request.getParameter("echostr");       // 随机字符串

//        if (StringUtil.isEmpty(signature)
//                || StringUtil.isEmpty(timestamp)
//                || StringUtil.isEmpty(nonce)
//                || StringUtil.isEmpty(echostr)) {
//            return "PARAMETER ERROR";
//        }

        log.info("验证微信公众号 => signature: {}, timestamp: {}, nonce: {}, echostr: {}", (Object[]) new String[] { signature, timestamp, nonce, echostr });

        // 通过检验 signature 对请求进行校验，若校验成功则原样返回 echostr，表示接入成功，否则接入失败
        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            log.info("验证微信公众号 => 结束 [验证通过]");
            return echostr;
        }

        log.info("验证微信公众号 => 结束 [验证失败]");
        return "AUTH ERROR";
    }

    /**
     * 描述：处理公众号消息
     *
     * @param
     * @return
     * @throws
     *
     * @author Westin Yang
     * @date 2017-03-31 19:37:57
     */
    @PostMapping
    public String post(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 调用核心业务类接收消息、处理消息
        String respMessage = wxCoreService.processRequest(request);

//        log.info("处理公众号消息 => respMessage:{}", respMessage);

        // 响应消息
        return respMessage;
    }

}
